package com.example.demomap;

import java.util.ArrayList;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl;
import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener;
import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperties;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTile;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTileProperty;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXTiledMap;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.util.Log;
import android.widget.Toast;

public class MainActivity extends BaseGameActivity {

    // ===========================================================
        // Constants
        // ===========================================================

        //private static final int CAMERA_WIDTH = 480;
        //private static final int CAMERA_HEIGHT = 320;
		private static final int CAMERA_WIDTH = 480;
		private static final int CAMERA_HEIGHT = 320;

        // ===========================================================
        // Fields
        // ===========================================================

        private Camera mCamera;
        private Texture mTexture;
        private TextureRegion mFaceTextureRegion;

        private Texture mOnScreenControlTexture;
        private TextureRegion mOnScreenControlBaseTextureRegion;
        private TextureRegion mOnScreenControlKnobTextureRegion;
       
        //Thêm code ở đoạn này
        private TMXTiledMap mTmxTiledMap;
        private TMXLayer VatCanTMXLayer;
        private String tenBanDo = "map_1.tmx";

        @Override
        public Engine onLoadEngine() {
            this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
            
            return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
        }

        @Override
        public void onLoadResources() {
            TextureRegionFactory.setAssetBasePath("gfx/");

            this.mTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "face_box.png", 0, 0);

            this.mOnScreenControlTexture = new Texture(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            this.mOnScreenControlBaseTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0);
            this.mOnScreenControlKnobTextureRegion = TextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0);

            this.mEngine.getTextureManager().loadTextures(this.mTexture, this.mOnScreenControlTexture);
        }

        @Override
        public Scene onLoadScene() {
            this.mEngine.registerUpdateHandler(new FPSLogger());

            final Scene scene = new Scene();
            scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
           
            //Tải map
            mTmxTiledMap = TaiBanDo.getTMXTiledMap(scene, mEngine, this, tenBanDo, this);
           
            // Lấy layer vật cản từ đối tượng mTMXTiledrMap
            ArrayList<TMXLayer> mapLayers = mTmxTiledMap.getTMXLayers();
            for(TMXLayer layer : mapLayers){
                //Nếu có layer nào tên như là "tuong" sẽ được lấy
                if(layer.getName().equals("tuong")){
                    VatCanTMXLayer = layer;
                }
                //Thêm vào cảnh trò chơi
                scene.attachChild(layer);
            }

            final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
            final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
            
            //final Sprite face = new Sprite(0,0, this.mFaceTextureRegion);
            final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion);
            final PhysicsHandler physicsHandler = new PhysicsHandler(face);
            face.registerUpdateHandler(physicsHandler);

            scene.attachChild(face);

            final DigitalOnScreenControl digitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() {
                @Override
                public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) {
                	
                    //Nếu bộ điều khiển nghiên về 1 trong 4 hướng
                    if(pValueX != 0 || pValueY != 0){
                    	/*Log.v("","X:" + MainActivity.this.mCamera.getCenterX() 
                    			+ ", Y:" + MainActivity.this.mCamera.getCenterY());*/
                    	/*if (pValueX == 1 && MainActivity.this.mCamera.getCenterX() < 752)
                    		MainActivity.this.mCamera.offsetCenter(32, 0);
                    	else if (pValueX == -1 && MainActivity.this.mCamera.getCenterX() > 240)
                    		MainActivity.this.mCamera.offsetCenter(-32, 0);
                    	else if (pValueY == 1 && MainActivity.this.mCamera.getCenterY() < 256)
                    		MainActivity.this.mCamera.offsetCenter(0, 32);
                    	else if (pValueY == -1 && MainActivity.this.mCamera.getCenterY() > 160)
                    		MainActivity.this.mCamera.offsetCenter(0, -32);*/
                    	/*if (pValueX == CAMERA_WIDTH)
                    	{
                    		CAMERA_WIDTH += 32;
                    		MainActivity.this.mCamera.setCenter(CAMERA_WIDTH, CAMERA_HEIGHT);
                    	}*/
                    	
                        float pX = 0, pY = 0;
                        //pX,pY là điểm tâm của Sprite face
                        pX = face.getX() + 16;
                        pY = face.getY() + 16;
                        Log.v("","X:" + pX + ", Y:" + pY);
                        //Dùng tâm của Sprite này để kiểm tra xem có va chạm với vật cản hay ko
                        TMXTile mTMXTile = VatCanTMXLayer.getTMXTileAt(pX, pY);
                        //Đoạn code này kiểm tra va chạm nè
                        try{
                            if(mTMXTile != null){
                                TMXProperties<TMXTileProperty> mTMXProperties = mTMXTile.getTMXTileProperties(mTmxTiledMap);
                                TMXProperty mTmxProperty = mTMXProperties.get(0);
                                if(mTmxProperty.getName().equals("vatcan")){
                                    Log.v("", "Chạm phải vật cản rồi !!!");
                                }
                            }
                        }catch(Exception e){
                            Log.v("", "Không có vật cản !!!");
                        }
                    }                   
                    physicsHandler.setVelocity(pValueX * 200, pValueY * 100);
                    
                    if(pValueX != 0 || pValueY != 0){
                    	Log.v("","X:" + face.getX() + ", Y:" + face.getY());
                    	changeCamera(face.getX(),face.getY());
                    }
                }
            });
            digitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
            digitalOnScreenControl.getControlBase().setAlpha(0.5f);
            digitalOnScreenControl.getControlBase().setScaleCenter(0, 128);
            digitalOnScreenControl.getControlBase().setScale(1.25f);
            digitalOnScreenControl.getControlKnob().setScale(1.25f);
            digitalOnScreenControl.refreshControlKnobPosition();

            scene.setChildScene(digitalOnScreenControl);

            return scene;
        }
        @Override
        public void onLoadComplete() {

        }
        
        public void changeCamera(double x, double y)
        {
        	if ((x+32) > (CAMERA_WIDTH - 96
        			+ MainActivity.this.mCamera.getCenterX() -240) && MainActivity.this.mCamera.getCenterX() < 752)
        		if (((x+32) - (CAMERA_WIDTH - 96
            			+ MainActivity.this.mCamera.getCenterX() -240) > 752))
        			MainActivity.this.mCamera.setCenter(752, MainActivity.this.mCamera.getCenterY());
        		MainActivity.this.mCamera.offsetCenter((float)((x+32) - (CAMERA_WIDTH - 96
            			+ MainActivity.this.mCamera.getCenterX() -240)), 0);
        		//MainActivity.this.mCamera.offsetCenter(32, 0);
	    	/*else if (pValueX == -1 && MainActivity.this.mCamera.getCenterX() > 240)
	    		MainActivity.this.mCamera.offsetCenter(-32, 0);
	    	else if (pValueY == 1 && MainActivity.this.mCamera.getCenterY() < 256)
	    		MainActivity.this.mCamera.offsetCenter(0, 32);
	    	else if (pValueY == -1 && MainActivity.this.mCamera.getCenterY() > 160)
	    		MainActivity.this.mCamera.offsetCenter(0, -32);*/
        }
}